<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Upload extends Controller {

	public function action_index()
	{

		$user = ORM::factory('user')
		->where('id', '=', Helper_User::get_logged())
		->find();
		
		$content = View::factory('template')
		->set('content',View::factory('forms/upload'))
		->set('left',	View::factory('menus/usermenu')
		->set('user',$user));
		$this->response->body($content);

	}

	public function action_post()
	{


			
		$str = file_get_contents($_FILES['torrent']['tmp_name']);
		$str = Lightbenc::bdecode($str);
		$str['announce'] = 'http://greem.dlinkddns.com/announce';
		unset ($str['announce-list']);
		//TODO вынести в настройки какой анонсер вставлять
		$file = ORM::factory('torrent');
		$file->name = $_POST['name'];
		$file->desc = $_POST['desc'];
		$file->info_hash = sha1(Lightbenc::bencode($str['info']));
		$file->uploader = '1';
		$file->poster = 'jpg';
		//TODO брать актуальные данные
		$file->save();
		$filename = $_SERVER['DOCUMENT_ROOT'] . '/torrents/' . $file->id . '.torrent';
		$str = Lightbenc::bencode($str);
		$bytes = file_put_contents($filename, $str, LOCK_EX);

		$pic = Upload::save($_FILES['poster'], $file->id . '.jpg','./torrents/posters/',0777);
		Image::factory($pic)->resize(100,NULL)->save('./torrents/posters/' . $file->id . '-small.jpg');



		print_r($_FILES['poster']);
		if  (isset($bytes)){
			$main = View::factory('forms/uploaded')
			->set('torrent', $file);
		}else {
			$main = View::factory('forms/uploaded')
			->set('errors', 'Что-то пошло не так!');

		}

		$user = ORM::factory('user')
		->where('id', '=', Helper_User::get_logged())
		->find();
		
		$content = View::factory('template')
		->set('content',$main)
		->set('left',	View::factory('menus/usermenu')
		->set('user',$user));
		$this->response->body($content);

	}
} // End Upload